<template>
    <!--
        部门选择器
        body-class="modalStyle" 表示样式
        size="lg" 表示模态窗口大小 xl,lg,sm,full
        hide-footer 表示隐藏底部按钮
        hide-header 表示隐藏头部内容
        no-close-on-backdrop 表示鼠标点击背景不可关闭
        hide-header-close 表示隐藏头部关闭按钮
        centered 居中
        ok-title=“确定” 
        cancel-title=取消
        @ok="handleOk" 
        @cancel="handleCancel"
        scrollable 滚动条
        hide-backdrop 隐藏背景
        wrapClassName="ant-modal-cust-warp" 
        style="top:5%;height: 85%;overflow-y: hidden" 样式
    -->
    <b-modal ref="my-modal" title="分配资源" scrollable no-close-on-backdrop>
        <div class="d-block text-center" id="roleResBody">
            <!--
                default-expand-all：默认全部展开
                show-checkbox:复选框
                :expand-on-click-node="false" 点击展开
                ref="roleResourcesTree" 定义属性
                :check-strictly="true" 选择子级默认选中父级，选中父级不选中子级
            -->
            <el-tree 
            :data="roleResourcesList" 
            node-key="id"
            :check-strictly="true"
            :default-expand-all="true" 
            :expand-on-click-node="false"
            :props="defaultProps"
            show-checkbox
            ref="tree"
            :default-checked-keys="selectTreeArr"
            @check="checkChange"
            ></el-tree>
        </div>
        <template slot="modal-footer">
            <!--自定义按钮-->
            <button type="button" class="btn btn-light-danger font-weight-bold mr-2" block @click="hideModal">
                <i class="icon-xl fa fa-times"></i>取消
            </button> 
            <button type="button" class="btn btn-light-success font-weight-bold mr-2"
            v-permission="{ action: '/oauthRole/saveOauthRR', effect: 'display' }"  
            @click="addXtMR">
                <i class="icon-xl fas fa-save"></i> 保存
            </button>
        </template>
    </b-modal>
</template>

<script>
import apiUtil from "@/core/util/apiUtil.js"; 
import { handleNotify,handleAlert,handleConfirm,showWating,closeWating} from "@/core/util/jehcUtil.js";
    export default {
        data() {
            return {
                roleResourcesList:[],
                roleObj:{},
                defaultProps: {
                    children: 'children',
                    checked:"checked",
                    label: 'text'
                },
                selectTreeArr: [], //选中的
            }
        },
        mounted() {
            
        },
        methods: {  
            checkChange(data) {
                const node = this.$refs.tree.getNode(data.id);
                this.setNode(node);
            },
            setNode(node) {
                console.log(node, "node");
                if (node.checked) {
                    //如果当前是选中checkbox,则递归设置父节点和父父节点++选中
                    this.setParentNode(node);
                } else {
                    //当前是取消选中,将所有子节点都取消选中
                    this.setChildenNode(node);
                }
            },
            setParentNode(node) {
            if (node.parent) {
                for (const key in node) {
                    if (key === "parent") {
                        node[key].checked = true;
                        this.setParentNode(node[key]);
                    }
                }
            }
            },
            setChildenNode(node) {
                let len = node.childNodes.length;
                for (let i = 0; i < len; i++) {
                    node.childNodes[i].checked = false;
                    this.setChildenNode(node.childNodes[i]);
                }
            },
            getInitCheckedAllNodes(node = [],arr=[]) {//查询初始化树中选择节点id
                for(let item of node) {
                    if(item.checked === true){
                        arr.push(item.id)
                    }
                    let parentArr = []
                    if(item.children) parentArr.push(...item.children)
                    if(parentArr && parentArr.length) this.getInitCheckedAllNodes(parentArr,arr) //递归查询
                    }
                    return arr
            },         
            showModal(row) {
                this.roleObj = row;
                this.initRoleResourcesList();
                this.$refs['my-modal'].show();
            },
            hideModal() {
                this.roleObj = {};
                this.$refs['my-modal'].hide()
            },
            toggleModal() {
                this.$refs['my-modal'].toggle('#toggle-btn')
            },
            addXtMR(data){
                // this.$emit("change",data);//组件传值，即向父级模态框中传递值，采用change方式
                // this.$refs['my-modal'].hide();
                if(!this.roleObj.id){
                    handleAlert("未能获取到权限id，不能保存！", "warning", 3)
                    return;
                }
                let resourcesId = this.$refs.tree.getCheckedKeys();
                if(resourcesId){
                    resourcesId = resourcesId.join(",")
                }
                // 保存前提示
                this.$confirm("确认保存吗?", "提示", {type: "warning",}).then(() => {
                    showWating({renderBody:"roleResBody",message:"正在执行分配操作,请稍后..."});
                    // 根据后台想要的参数格式选择                    
                    let params = {resourcesId:resourcesId,roleId:this.roleObj.id};
                    apiUtil.update(process.env.VUE_APP_OAUTH_API+"/oauthRole/saveOauthRR",params).then(data=>{
                        if(data.data.success){
                            handleAlert("保存成功", "success", 3);
                        }else {
                            handleAlert("保存失败", "error", 3);
                        }
                    });
                }).catch(()=>{});//注意这里，这里是重点！！！; 
            },
            expandAll() {
                //展开全部
                for (var i in this.$refs.tree.store.nodesMap) {
                    this.$refs.tree.store.nodesMap[i].expanded = true;
                }
                //收起
                // for (var j in this.$refs.tree.store.nodesMap) {
                //     this.$refs.tree.store.nodesMap[j].expanded = false;
                // }
            },
            initRoleResourcesList(){
                let params = {};
                apiUtil.query(process.env.VUE_APP_OAUTH_API+"/oauthRole/resources?roleId="+this.roleObj.id+"&sysModeId="+this.roleObj.sysModeId, params).then(({ data }) => {
                    let result = JSON.parse(data.data);
                    this.roleResourcesList = result;                       
                    let nodes = this.getInitCheckedAllNodes(result);
                    this.$refs.tree.setCheckedKeys(nodes) // 选中要选择的数据
                });
            }
        }
    }
</script>